using System.Collections.Generic;
using System.Text;

namespace SharpObjects.XpathToObjects
{
    public static class ListExtensions
    {
        public static object Last(this List<object> list)
        {
            if(list != null && list.Count > 0)
            {
                return list[list.Count - 1];
            }
            else
            {
                return null;
            }
        }

        public static object First(this List<object> list)
        {
            if (list != null && list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        public static string Xpath(this List<PathElement> xpath)
        {
            StringBuilder sb = new StringBuilder();

            foreach (PathElement pathElement in xpath)
            {
                if(pathElement.ElementType != PathElement.ePathElementType.Root && pathElement.ElementType != PathElement.ePathElementType.AnyPlace)
                {
                    sb.Append('/');
                }

                sb.Append(pathElement.Text);
            }

            return sb.ToString();
        }

        public static List<object> Clone(this List<object> list)
        {
            List<object> clone = new List<object>(list.Count);

            foreach (object obj in list)
            {
                clone.Add(obj);
            }

            return clone;
        }

        public static List<object> CloneAndOnlyKeepFirst(this List<object> list)
        {
            List<object> clone = new List<object>(1);
            clone.Add(list.First());
            return clone;
        }
    }
}